<?php

namespace app\queue;

use app\constant\ModelConstant;
use app\event\PushOrderToShopify;
use app\helpers\RedisLock;
use app\libs\PaypalSDK\action\PurchasePaypal;
use app\model\Orders;
use app\model\ShopsPayment;
use app\trait\PaymentTrait;
use think\facade\Event;
use think\helper\Arr;
use think\queue\Job;

class CapturePaymentQueue
{
    use PaymentTrait;
    protected Orders $order;
    protected array $request;
    public function fire(Job $job, $data)
    {
        if(empty($data) || !isset($data['order_id'])){
            $job->delete();
            return false;
        }
        $cacheKeys = "order_checkout_". $data['order_id'];
        $lock = new RedisLock($cacheKeys,10);
        try{
            if($lock->acquire()) {//加锁
                $this->run($data);
                $lock->release();
            }
            $lock->release();
            $job->delete();
        }catch (\Exception $e){
            $lock->release();
            dump($e->getMessage());
            $job->delete();
        }

    }

    public function run($data)
    {
        dump('***************正在执行订单ID: ' . $data['order_id'] . ' *********支付');
        $order_id = $data['order_id'];
        $this->request = $data['request'] ?? [];
        $this->order = Orders::findOrEmpty($order_id);
        if ($this->order->isEmpty()) return true;
        if(is_null($this->order)) return true;//订单是NULL 问题
        try {
                if ($this->order->is_support_repurchase) {
                    dump('未完成');
                    if ($this->order->is_completed && $this->order->order_status == Orders::ORDER_STATUS_COMPLETED) {
                        dump("已完成");
                        return false;
                    }
                } else {
                    if ($this->order->order_status == Orders::ORDER_STATUS_COMPLETED) return true;
                }
                $payment = $this->order->payment;
                switch ($payment->pay_method) {
                    case ShopsPayment::PAY_METHOD_PAYPAL:
                        $result = $this->handleWithPaypal();
                        break;
                    case ShopsPayment::PAY_METHOD_ASIABILL:
                        $result = $this->handleWithAsiabill();
                        break;
                    case ShopsPayment::PAY_METHOD_PAYONEER:
                        $result = $this->handleWithPayoneer();
                        break;
                    default:
                        $result = true;
                }

                if ($result) {
                    $this->order->pay_status = Orders::ORDER_STATUS_COMPLETED;
                    $this->order->save();
                    //队列处理订单
                    if (!$this->order->is_support_repurchase) {
                        dump("******************上传shopify订单*****************");
                        //event('PushOrder', $this->order);
                        Event::trigger("PushOrder",new PushOrderToShopify($this->order));
                    }
                }
                return $result;
        }catch (\Exception $e){
            tplog('capture order',$e->getMessage());
            if($this->order->order_status != Orders::ORDER_STATUS_COMPLETED) {
                $this->order->order_status = Orders::ORDER_STATUS_FAIL;
            }
            $this->order->error_msg = $e->getMessage();
            $this->order->save();
            throw new \Exception($e->getMessage());
        }
    }

    //paypal
    protected function handleWithPaypal()
    {
        dump('*****************paypal支付: order_id: ' . $this->order->id . ', transaction_id: '. $this->request['token']);
        return $this->executePaypalCapture($this->order,$this->request['token']);
    }

    //asiabill
    protected function handleWithAsiabill()
    {
        $data = $this->request['data'] ?? [];
        if(empty($data)) return false;
        $orderStatus = $data['orderStatus'];
        return $orderStatus == 'success';
    }

    //payoneer
    protected function handleWithPayoneer()
    {
        return true;
    }

}